import { Context, NextFunction } from '@midwayjs/koa'
import { CacheManager } from '@ttou/midway-cache'

import { APP_MESSAGES } from '@/constant'

interface CacheOptions {
  /**
   * 缓存键名
   */
  key: string | ((ctx: Context) => string)
  /**
   * 有效期，单位ms
   */
  ttl: number
}

export function CacheMiddleware(options: CacheOptions) {
  const fnMiddleware = async function (ctx: Context, next: NextFunction) {
    const cacheManager = await ctx.requestContext.getAsync(CacheManager)
    const logger = ctx.getLogger()

    const cacheKey =
      typeof options.key === 'string' ? options.key : options.key(ctx)

    const cacheValue = await cacheManager.get<any>(cacheKey)

    // 命中缓存
    if (cacheValue) {
      logger.debug(APP_MESSAGES.CACHE_EXIST)
      return cacheValue
    }

    const data = await next()

    try {
      await cacheManager.set(cacheKey, data, options.ttl)
    } catch (error) {
      console.error(error)
    }
  }

  fnMiddleware._name = CacheMiddleware.name

  return fnMiddleware
}
